<?php

namespace app\admin\controller;

use app\admin\validate\CompanyValidate;
use app\common\model\Company as CompanyModel;
use app\common\controller\AdminController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="公司管理")
 */
class Company extends AdminController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model        = new CompanyModel();
        $this->joinTable    = 'group,user';
        $this->joinAddTable = 'user';
        //        $this->validateClass = CompanyValidate::class;
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post         = $request->post();
        $post['user'] = json_decode($post['user'], true);
        $rule         = [
                'name|公司名称'          => 'require|max:100|unique:company,name,group_id^delete_time',
                'contact|负责人名称'     => 'require|max:100',
                'phone|负责人电话'       => 'require|max:20|unique:company,phone,group_id^delete_time',
                'user.username|用户名称' => 'require|max:100|unique:company_user,username^delete_time',
                'user.phone|用户手机号'  => 'require|mobile|unique:company_user,phone^delete_time',
        ];
        $this->validate($post, $rule);
        try {
            $post['group_id'] = $this->groupId;
            $this->model->transaction(function () use ($post, &$save)
            {
                $tableField = $post['user'];
                $save       = $this->model->save($post);
                if (empty($tableField['password'])) $tableField['password'] = '123456';
                $tableField['password'] = password($tableField['password']);
                if ($save) {
                    $this->model->user()->save($tableField);
                }
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        if ($save) return $this->success('新增成功');
        return $this->error('新增失败');
    }
}